import * as Cesium from 'cesium'

export default async function add3DTiles() {
  const customShader = new Cesium.CustomShader({
    uniforms: {
      minHeight: {
        type: Cesium.UniformType.FLOAT,
        value: 0.0
      },
      maxHeight: {
        type: Cesium.UniformType.FLOAT,
        value: 0.0
      }
    },
    mode: Cesium.CustomShaderMode.MODIFY_MATERIAL,
    lightingModel: Cesium.LightingModel.PBR,
    translucencyMode: Cesium.CustomShaderTranslucencyMode.TRANSLUCENT,
    vertexShaderText: `
      void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput) {
      }
    `,
    fragmentShaderText: `
      void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
        // vec4 position = czm_inverseModelView * vec4(v_positionEC, 1.0);
        // v_positionEC 是在观察空间（摄像机空间）中的位置，而 v_positionMC 是在模型空间中的位置
        float strength = (v_positionMC.z - minHeight)/ (maxHeight - minHeight);
        // float strength = (position.z - minHeight)/ (maxHeight - minHeight);
        float r  = fract(0.01 * czm_frameNumber);
        vec4 centerColor = vec4(0.0, 0.95, 1.0, 1.0);
        float ratio = smoothstep(r, r + 0.02, strength) - smoothstep(r + 0.025, r + 0.03, strength);
        material.diffuse = vec3(mix(material.diffuse, centerColor.rgb, ratio));
        material.alpha = 0.5;
      }
    `,
  })
  const tileset = await Cesium.Cesium3DTileset.fromUrl(
    "/Tileset/tileset.json", {
      customShader: customShader
  })

  window.viewer.scene.primitives.add(tileset)
  let [minHeight, maxHeight] = [tileset.properties.Height.minimum, tileset.properties.Height.maximum]
  console.log(minHeight, maxHeight)
  tileset.customShader.setUniform('minHeight', minHeight)
  tileset.customShader.setUniform('maxHeight', maxHeight)
  console.log(tileset.properties)
  // 视图定位
  window.viewer.zoomTo(tileset, new Cesium.HeadingPitchRange(
    0.0, -0.5, tileset.boundingSphere.radius * 2.0
  ))
}
